// class ClickDebugBehaviour extends Behaviour {

//     onStart() {
//         this.gameObject.onClick = function () {
//             console.log('click me!!!')
//         }
//     }
// }

// core.registerBehaviourClass(ClickDebugBehaviour);

//开始场景的点击事件
class StartSceneEvent extends Behaviour {

    onStart() {
        const startButton = core.getObjectById("startButton");
        const backButton = core.getObjectById("backButton");
        const staffButton = core.getObjectById("staffIntroduction");
        const bg = core.getObjectById("background");
        const introductionUI = core.getObjectById("introductionUI");

        introductionUI.setActive(false);
        backButton.setActive(false);
        if (startButton) {
            startButton.onClick = function () {
                player.init_player();

                core.changeScene("game.json")
            }
        }
        else console.log("没找到开始游戏按钮");

        if (backButton) {
            backButton.onClick = function () {
                bg.setActive(true);
                introductionUI.setActive(false);
                backButton.setActive(false);
                startButton.setActive(true);
                staffButton.setActive(true);


            }
        }
        if (staffButton) {
            staffButton.onClick = function () {
                bg.setActive(false);
                introductionUI.setActive(true);
                backButton.setActive(true);
                startButton.setActive(false);
                staffButton.setActive(false);


            }
        }

    }
}

let endchoose: number = 1;
class EndSceneEvent extends Behaviour {

    imagerender: ImageRenderer;
    onStart() {
        const backButton = core.getObjectById("backButton");
        const bg = core.getObjectById("background");
        this.imagerender = bg.getBehaviour(ImageRenderer);
        switch (endchoose) {
            case 1:
                this.imagerender.image = "assets/startScene/END_01.png";
                break;
            case 2:
                this.imagerender.image = "assets/startScene/END_02.png";
                break;
            case 3:
                this.imagerender.image = "assets/startScene/END_03.png";
                break;
            case 4:
                this.imagerender.image = "assets/startScene/END_04.png";
                break;
        }

        if (backButton) {
            backButton.onClick = function () {
                core.changeScene('prefab/startScene.json');

            }
        }
    }


}

class Keycontrol { //用来响应多个摁键同时摁下

    isapressing: boolean = false;
    isdpressing: boolean = false;
    isshiftpressing: boolean = false;
    isspaceressing: boolean = false;
    isfpressing: boolean = false;

    start() {
        window.addEventListener("keydown", (e) => {
            if (e.key == "a") {
                this.isapressing = true;

            }
            if (e.key == 'd') {
                this.isdpressing = true;

            }
            if (e.keyCode == 32) {
                this.isspaceressing = true;

            }
            if (e.keyCode == 16) {
                this.isshiftpressing = true;

            }
            if (e.key == "f") {
                this.isfpressing = true;
            }
        });

        window.addEventListener("keyup", (e) => {
            if (e.key == "a") {
                this.isapressing = false;
            }
            if (e.key == 'd') {
                this.isdpressing = false;
            }
            if (e.keyCode == 32) {
                this.isspaceressing = false;
            }
            if (e.keyCode == 16) {
                this.isshiftpressing = false;
            }
            if (e.key == "f") {
                this.isfpressing = false;
            }
        });
    }


}



class PeopleControl extends Behaviour {//角色控制类 （全部控制大类）

    private currentTime = 0;
    private keycontrol = new Keycontrol();
    private staus = 0;
    private Xcollider = false;
    private Ycoolider = false;
    private colliders: Collider_Object[] = [];
    private istake: boolean[] = [];//记录是否到达过此选项节点，避免重复
    private dialog: GameObject;
    private map_delta_y: number = 0;
    private collide_direction: boolean[] = [false, false, false, false];
    private start_y: number = null;
    private end_y: number = null;
    private first_frame: boolean = true;
    private ischanging: boolean = false;
    public endChoose: number = 1;

    constructor(private map: GameObject) {
        super();
        this.dialog = core.getObjectById("dialog");
        if (this.dialog)
            this.dialog.setActive(false);
    }

    collider_with_move() {

    }
    getAnimation() {
        return this.gameObject.getBehaviour(PlayerAnimation);
    }
    getimagerender() {
        return this.gameObject.getBehaviour(ImageRenderer);
    }
    $getTransform() {

        return this.gameObject.getBehaviour(Transform);

    }
    onStart() {
        if (!player.isdead) {
            this.keycontrol.start();
        }
    }



    async dialog_button_control(id: number) { //控制对话及选项


        if (!this.istake[id]) {

            if (!this.dialog.$isActive) {

                this.dialog.setActive(true);
            }
            player.is_move = false;
            player.dialog = new dilog_and_button(this.dialog.$children[0], this.dialog.$children[1], this.dialog.$children[2],
                this.dialog.$children[3], this.dialog.$children[4], id);

            await player.dialog.execute();
            this.istake[id] = true;

        }
        else {
            this.dialog.setActive(false);

        }
    }


    age_stage_change(stage: number) { //控制幼年、少年、青年、中年、老年阶段转化

        switch (stage) {
            case 0: player.mainRole.state = 0
                break
            case 1: player.mainRole.state = 1

                break;
            case 2: player.mainRole.state = 2
                break;
            case 3: player.mainRole.state = 3
                break;
            case 4: player.mainRole.state = 4
                break;
        }

    }

    camera_move(gameobject: GameObject, map: Transform, user: Transform) {
        this.start_y = this.end_y;
        this.end_y = gameobject.getBehaviour(Transform).y + gameobject.parent.getBehaviour(Transform).y;
        if ((this.start_y != null) && (this.end_y != null)) {
            // console.log("start"+this.start_y);
            // console.log("end"+this.end_y);
            map.y += (this.start_y - this.end_y);
            user.y += (this.start_y - this.end_y);
            // if (this.start_y > this.end_y) {
            //     this.map.getBehaviour(Transform).y += this.start_y - this.end_y;
            //     console.log("屏幕向下");
            // } else {
            //     this.map.getBehaviour(Transform).y += this.start_y - this.end_y;
            //     console.log("屏幕向上");
            // }
        }

    }

    movestop(gameobect: GameObject, direction: boolean[], Box: Box) {
        if (direction[0]) {
            this.collide_direction[0] = true;
        }
        if (direction[1]) {
            this.collide_direction[1] = true;
            player.box = Box;
            this.camera_move(gameobect, this.map.getBehaviour(Transform), this.gameObject.getBehaviour(Transform));

        }
        if (direction[2]) {
            this.collide_direction[2] = true;
        }
        if (direction[3]) {
            this.collide_direction[3] = true;
        }


    }
    onDestroy() {

    }


    onUpdate(duringTime) {

        this.colliders = this.gameObject.getBehaviour(Colliderer).onCollision();
        const transform = this.$getTransform();
        const imagerender = this.getimagerender();
        const animatior = this.getAnimation();





        if (this.colliders != null) {//遍历
            for (let collider of this.colliders) {
                switch (collider.gameobject.tag) {
                    case "box":
                        this.movestop(collider.gameobject, collider.collider_direction, collider.gameobject.getBehaviour(Box));//判断人物哪个面收到碰撞。
                        break;
                    case "stage":
                        if (player.mainRole.state == 0) {
                            transform.y -= 130;
                            this.ischanging = true;
                        }
                        this.age_stage_change(collider.gameobject.grade - 1);

                        break;
                    case "dialog":
                        this.dialog_button_control(collider.gameobject.grade - 1);
                        break;
                    case "finish":
                        endchoose = collider.gameobject.grade
                        core.changeScene('prefab/endScene.json');
                        player.init_player();
                        break;
                }
            }
        }



        if (player.mainRole.move_direction) {
            imagerender.image = animation[player.mainRole.state * 2][0];//图片转换
            transform.width = getImage(animation[player.mainRole.state * 2][0]).width;
            transform.height = getImage(animation[player.mainRole.state * 2][0]).height;
        } else {
            imagerender.image = animation[player.mainRole.state * 2 + 1][0];//图片转换
            transform.width = getImage(animation[player.mainRole.state * 2 + 1][0]).width;
            transform.height = getImage(animation[player.mainRole.state * 2 + 1][0]).height;
        }


        if (player.is_move) {
            if (this.keycontrol.isapressing) {

                player.mainRole.move_direction = true;
                animatior.playAnimation(player.mainRole.image);
                if (transform.x % 800 >= 100) {
                    player.walk(transform, duringTime, false, this.collide_direction[2]);

                }
                else {
                    player.walk(this.map.getBehaviour(Transform), duringTime, true, this.collide_direction[2]);

                }

            }
            if (this.keycontrol.isdpressing) {
                player.mainRole.move_direction = false;
                animatior.playAnimation(player.mainRole.image);

                if (transform.x % 800 <= 600) {
                    player.walk(transform, duringTime, true, this.collide_direction[3]);
                }
                else {
                    player.walk(this.map.getBehaviour(Transform), duringTime, false, this.collide_direction[3]);
                }
            }
            if (this.keycontrol.isspaceressing && !player.isjumping && !player.isdropping) {
                player.isjumping = true;
                this.keycontrol.isspaceressing = false;
            }
        }





        if (player.isjumping) {
            player.jump(transform, duringTime, this.collide_direction[0]);

        }
        // if (transform.y < 300) {//需要修改
        //     this.map.getBehaviour(Transform).y += player.movespeed * duringTime / 1000;
        // }
        if (transform.y > 1200) {
            player.isdead = true;
        }

        if (player.mainRole.state == 0) { //调整角色图片的大小宽度
            transform.width = 48;
            transform.height = 29;
        }

        if (!this.ischanging)
            player.drop(transform, duringTime, this.collide_direction[1]);

        this.ischanging = false;
        this.collide_direction.splice(0);
    }

}


class ClickContainerBehaviour extends Behaviour {


    onStart() {
        this.gameObject.onClick = () => {

        }

    }
}




class MoveBehaviour extends Behaviour {

    @SerializedField(1000)
    time: number;

    @SerializedField(0)
    targetX: number;

    private currentTime = 0;
    private initX = 0;
    private initY = 0;
    onStart() {
        this.initX = this.$getTransform().x;
        this.initY = this.$getTransform().y;
    }

    $getTransform() {
        return this.gameObject.getBehaviour(Transform);
    }

    onUpdate(duringTime) {
        const transform = this.$getTransform();
        this.currentTime += duringTime;
        let timeRatio = this.currentTime / this.time;
        if (timeRatio > 1) {
            timeRatio = 1;
        }
        const needToMoveX = this.targetX - this.initX;
        transform.x = this.initX + timeRatio * needToMoveX;
        if (timeRatio == 1) {
            this.gameObject.removeBehaviour(this);
        }
    }

    onDestroy() {

    }
}



class GameStartupBehaviour extends Behaviour {


    AddToChangeObject(gameobect, changObject) {

        for (let child of gameobect.$children) {

            if (child.situation != 0) {
                child.setActive(false);
                changObject[child.situation - 1].push(child);
            }

            if (child.$children != []) {
                this.AddToChangeObject(child, changeGameobjet);
            }
        }

    }

    onStart() {

        const player = core.getObjectById('kid');
        const control = new PeopleControl(core.getObjectById('map'));
        player.addBehaviour(control);
        player.setActive(true);
        this.AddToChangeObject(core.getObjectById("map"), changeGameobjet);

        endchoose = 1;


    }

    onUpdate() {
        this.set_box_speed_intex();

        if (player.isdead) {
            player.init_player();
            core.changeScene('game.json');
        }

    }

    set_box_speed_intex() {
        if (!player.box) {
            player.box_speed_intex = 1;
        } else {
            player.box_speed_intex = player.box.speedintex_box();
        }
    }

}

//注册对应的行为

core.registerBehaviourClass(StartSceneEvent);
core.registerBehaviourClass(ClickContainerBehaviour);
core.registerBehaviourClass(MoveBehaviour);
core.registerBehaviourClass(GameStartupBehaviour);
core.registerBehaviourClass(EndSceneEvent);
core.registerBehaviourClass(PeopleControl);